package com.example.fourm.services.impl;

import com.example.fourm.common.AppResult;
import com.example.fourm.common.ResultCode;
import com.example.fourm.dao.UserMapper;
import com.example.fourm.exception.ApplicationException;
import com.example.fourm.model.User;
import com.example.fourm.services.IUserService;
import com.example.fourm.utils.MD5Util;
import com.example.fourm.utils.StringUtil;
import com.example.fourm.utils.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.transform.Result;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 注册功能
     * @param user 传入的用户user
     */
    @Override
    public void createNormalUser(User user) {
        //1、非空校验
        if(StringUtil.isEmpty(user.getUsername())||StringUtil.isEmpty(user.getPassword())
        ||StringUtil.isEmpty(user.getNickname())||StringUtil.isEmpty(user.getSalt())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2、用户已经存在的情况
        User existUser = userMapper.selectByUserName(user.getUsername());
       if(existUser!=null) {
           log.error(ResultCode.AILED_USER_EXISTS.getMessage());
           throw new ApplicationException(AppResult.failure(ResultCode.AILED_USER_EXISTS));
       }
       //3、进行新增用户的操作
       user.setGender((byte) 2);
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int insert = userMapper.insertSelective(user);
        if(insert != 1){
            log.warn(ResultCode.FAILED_CREATE.getMessage());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_CREATE));
        }
        log.info(ResultCode.SUCCESS.getMessage());
    }

    /**
     * 通过username查询用户
     * @param username
     * @return 返回用户信息
     */
    @Override
    public User selectByUserName(String username) {
        //参数校验
        if(StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()+"username: "+username);
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByUserName(username);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        return user;
    }

    /**
     * 判断登录的用户信息是否正确
     * @param username
     * @param password
     * @return 返回use对象，controller层需要使用user存储在session中
     */
    @Transactional //在测试方法上加事务注解，完成后会发生回滚操作，不会污染数据库
    @Override
    public User selectByUserName(String username, String password) {
        //参数校验
        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()+"username: "+username);
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户信息
        User user = selectByUserName(username);
        //对查询的信息进行非空校验
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验密码是否正确
        String encryPassword = MD5Util.md5(password, user.getSalt());
        if (!encryPassword.equals(user.getPassword())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()+",密码错误");
            throw new ApplicationException(AppResult.failure("密码错误"));
        }
        return user;
    }

    @Override
    public User selectByPrimaryKey(Long id) {
        if(id==null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()+"id: "+id+"为空");
            throw new ApplicationException(AppResult.failure("id为空"));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id < 1 || id == null){
            log.warn("id不合法");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
       User user = selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage()+"用户不存在！");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setArticleCount(user.getArticleCount()+1);
        userMapper.updateByPrimaryKeySelective(newUser);
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id < 1 || id == null){
            log.warn("id不合法");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage()+"用户不存在！");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setArticleCount(user.getArticleCount()-1);
        if(user.getArticleCount()<=0){
            newUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(newUser);
        if(row!=1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
    }
    }

    @Override
    public void modifyInfo(User user) {
        if (user == null || user.getId() == null || user.getId()<= 0) {
            log.warn("id不合法");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user1 = userMapper.selectByPrimaryKey(user.getId());
        if(user1==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage()+"用户不存在！");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        boolean checkAttr = false;//标志位 检验是否验证通过，当有一个参数不为空则为true
        User newUser = new User();//用来更新的对象
        newUser.setId(user.getId());
        if(!StringUtil.isEmpty(user.getUsername()) && !user.getUsername().equals(user1.getUsername())){
            //先查用户名是否唯一
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser!=null){
                log.warn("该用户名已存在！");
                throw new ApplicationException(AppResult.failure(ResultCode.AILED_USER_EXISTS));
            }
            newUser.setUsername(user.getUsername());
            checkAttr = true;
        }
        if(!StringUtil.isEmpty(user.getNickname()) && !user.getNickname().equals(user1.getNickname())){
            newUser.setNickname(user.getNickname());
            checkAttr = true;
        }
       if(user.getGender()!= null && !user.getGender().equals(user1.getGender())){
           newUser.setGender(user.getGender());
           checkAttr = true;
       }
       if(!StringUtil.isEmpty(user.getEmail()) && !user.getEmail().equals(user1.getEmail())){
           newUser.setEmail(user.getEmail());
           checkAttr = true;
       }
        if(!StringUtil.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(user1.getPhoneNum())){
            newUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
        if(!StringUtil.isEmpty(user.getRemark()) && !user.getRemark().equals(user1.getRemark())){
            newUser.setRemark(user.getRemark());
            checkAttr = true;
        }
        if(checkAttr == false){
            log.warn("没有要更新的信息");
            throw new ApplicationException("没有要更新的资源");
        }
        int row = userMapper.updateByPrimaryKeySelective(newUser);
        if(row!=1){
            log.warn("更新失败！");
            throw new ApplicationException("更新失败！");
        }
        log.info("更新成功！！");
    }

    @Override
    public void modifyPassword(Long id, String oldPassword, String newPassword) {
        if(id == null || id<= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验老密码是否正确
        String encry = MD5Util.md5(oldPassword, user.getSalt());
        if(!encry.equals(user.getPassword())){
            log.warn("旧密码不正确");
            throw new ApplicationException(AppResult.failure("旧密码不正确"));
        }
        String salt = UUIDUtil.UUID_32();
        String password = MD5Util.md5(newPassword, salt);
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setSalt(salt);
        newUser.setPassword(password);
        int row = userMapper.updateByPrimaryKeySelective(newUser);
        if(row!=1){
            log.warn("更新失败！");
            throw new ApplicationException("更新失败！");
        }
        log.info("密码更新成功！！");
    }


}
